package com.bulletelc.apollopre.module.display.product.details.introduce;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.entity.OrderConfirmBean;
import com.bulletelc.apollopre.entity.ProductDetailAll;
import com.bulletelc.apollopre.framework.BasePresenter;
import com.bulletelc.apollopre.utils.LogUtil;
import com.bulletelc.apollopre.utils.MyUtil;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.GetRequest;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * author: lhl
 * date  : 2018/01/15
 * desc  : TODO
 */

public class IntroducePresenter extends BasePresenter<IntroduceContract.View> implements IntroduceContract.Presenter {

    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public void addCart(String json, String token) {
        addCartImp(json,token);
    }

    @Override
    public void buyNow(String json, String token) {
        buyNowImp(json, token);
    }

    @Override
    public void getProductDetails(String productId) {
        getDetail(productId);
    }

    /**
     * 获取产品详情
     */
    private void getDetail(String productId) {
        String uid = MyApplication.getUserId();
        GetRequest<String> request = OkGo.<String>get(NetWorkPath.GET_PRODUCT_DETAIL).params("id", productId);
        request.params("expand", "description");
        if (uid != null) {
            request.params("uid", MyApplication.getUserId());
        }
        request.execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                parseData(response);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                if (isViewAttached()) {
                    getView().onError(response.getException().toString());
                }
            }
        });
    }

    /**
     * 解析数据
     */
    private void parseData(Response<String> response) {
        try {
            JSONObject object = new JSONObject(response.body().toString());
            JSONObject metaObj = object.getJSONObject("meta");
            String code = metaObj.getString("code");
            if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(code)) {

                Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
                    @Override
                    public boolean shouldSkipField(FieldAttributes f) {
                        return f.getName().contains("_links");// 过滤不需要参数
                    }

                    @Override
                    public boolean shouldSkipClass(Class<?> clazz) {
                        return false;
                    }
                }).create();

                ProductDetailAll productDetailAll = gson.fromJson(object.getJSONObject("data").toString(), ProductDetailAll.class);
                if (isViewAttached()) {
                    getView().onSuccess(productDetailAll);
                }

            } else {
                if (isViewAttached()) {
                    getView().onFail(metaObj.getString("msg"));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            if (isViewAttached()) {
                getView().onError("数据解释错误");
            }
        }
    }

    /**
     * 添加到购物车
     * @param json
     */
    private void addCartImp(String json,String token) {
        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), json);
        OkGo.<String>post(NetWorkPath.POST_CART_UPDATE)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken(token))
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseAddCart(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorAddCart(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析加入购物车返回数据
     * @param response
     */
    private void parseAddCart(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                String code = metaObj.getString("code");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(code)) {
                    if (isViewAttached()) {
                        getView().onSuccessAddCart();
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailAddCart(metaObj.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorAddCart("数据解释错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailAddCart(response.body().toString());
            }
        }
    }

    /**
     * 立即购买
     */
    private void buyNowImp(String json, String token) {
        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), json);
        OkGo.<String>post(NetWorkPath.POST_BUY_NOW)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken(token))
                .params("eshop_id",1) //平台id默认1
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        //LogUtil.i(response.body().toString());
                        parseDataBuyNow(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorBuyNow(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析立即购买返回的数据
     * @param response
     */
    private void parseDataBuyNow(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                String code = metaObj.getString("code");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(code)) {
                    Gson gson = new Gson();
                    OrderConfirmBean confirmBean=gson.fromJson(object.getJSONObject("data").toString(), OrderConfirmBean.class);
                    if (isViewAttached()) {
                        getView().onSuccessBuyNow(confirmBean);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailAddCart(metaObj.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorAddCart("数据解释错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailBuyNow(response.body().toString());
            }
        }
    }

}
